/*
 *
 *      Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: lengleng (wangiegie@gmail.com)
 *
 */

package com.hibase.core.log.aspect;

import com.hibase.core.log.annotation.HibaseLog;
import com.hibase.core.log.entity.MdsOperationLog;
import com.hibase.core.log.event.HibaseLogEvent;
import com.hibase.core.log.service.MdsOperationLogService;
import com.hibase.core.log.util.HibaseLogUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;

import java.math.BigDecimal;

/**
 * 操作日志使用spring event异步入库
 *
 * @author L.cm
 */
@Slf4j
@Aspect
@RequiredArgsConstructor
public class HibaseLogAspect {

	private final ApplicationEventPublisher publisher;

	@Autowired
	private MdsOperationLogService mdsOperationLogService;
	
	@SneakyThrows
	@Around("@annotation(hibaseLog)")
	public Object around(ProceedingJoinPoint point, HibaseLog hibaseLog) {
		String strClassName = point.getTarget().getClass().getName();
		String strMethodName = point.getSignature().getName();
		log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);

		MdsOperationLog operationLog = HibaseLogUtil.getOperationLog();
		operationLog.setRemarks(hibaseLog.value());
		operationLog.setSource(hibaseLog.source());
		operationLog.setType(hibaseLog.type());
		// 发送异步日志事件
		Long startTime = System.currentTimeMillis();
		Object obj = point.proceed();
		Long endTime = System.currentTimeMillis();
		operationLog.setTime(new BigDecimal(endTime-startTime));
		publisher.publishEvent(new HibaseLogEvent(operationLog));
		
		mdsOperationLogService.store(operationLog);
		return obj;
	}

}
